package com.block.datapush.form.item;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.service.LogFactory;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.form.item.util.HappyUtil;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 快乐分期 表单推送
 * 文档地址：https://www.showdoc.com.cn/1353427028638416/6706582082080321
 */
@Service
public class HappyPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getPushLog();

    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) throws Exception {

            String queryUrl = formInfo.getQueryUrl();
            String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();

            Map<String, Object> bizParamMap = new HashMap<>();
            bizParamMap.put("mobile_md5", mobileMd5);

            Long timestamp = System.currentTimeMillis();

            String sign = this.getSignResult(formInfo.getApiKey(), timestamp, formInfo.getApiSecret());
            String bizParam = this.getBizParamEncrypt(mobileMd5, formInfo.getApiSecret());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("channel", formInfo.getApiKey());
            paramMap.put("timestamp", timestamp);
            paramMap.put("sign", sign);
            paramMap.put("bizParam", bizParam);
//            paramMap.putAll(bizParamMap);

            log.info("【快乐分期】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【快乐分期】撞库结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);
            Integer status = resultObject.getInteger("status");
            String info = resultObject.getString("info");
            JSONObject data = resultObject.getJSONObject("data");

            if (ObjectUtil.equal(status, Integer.valueOf(1))){
                Integer code = data.getInteger("code");
                if (ObjectUtil.equal(code, Integer.valueOf(1))){
                    return true;
                }
            }
            return false;
    }

    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject jsonObject) throws Exception {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);

            String queryUrl = formInfo.getRequestUrl();
            Map<String, Object> bizParamMap = new HashMap<>();

            bizParamMap.put("demand_amount", HappyUtil.getLoanAmount(memberExtInfo.getLoanAmount()));// 申请金额
            bizParamMap.put("fund", HappyUtil.getGjj(memberExtInfo.getGjj()));// 公积金
            bizParamMap.put("social", HappyUtil.getShebao(memberExtInfo.getSocialInsurance()));// 社保
            bizParamMap.put("insurance", HappyUtil.getBaodan(memberExtInfo.getInsurance()));// 保险
            bizParamMap.put("zhima_score", HappyUtil.getZhima(memberExtInfo.getZhimaScore()));// 芝麻
            bizParamMap.put("huabei", HappyUtil.getHuabei(memberExtInfo.getHuabei()));// 花呗
            bizParamMap.put("baitiao", HappyUtil.getBaitiao(memberExtInfo.getBaitiao()));// 白条
            bizParamMap.put("house", HappyUtil.getHouse(memberExtInfo.getHouse()));// 房产情况
            bizParamMap.put("car", HappyUtil.getCar(memberExtInfo.getCar()));// 车产情况
            bizParamMap.put("credit_card_overdue", HappyUtil.getYuqi(memberExtInfo.getYuqi()));// 信用逾期情况
            bizParamMap.put("city_name", HappyUtil.getCityName(memberExtInfo.getProvince(),memberExtInfo.getCity()));// 城市
            bizParamMap.put("realname", memberExtInfo.getUsername());// 姓名
            bizParamMap.put("id_card_no", memberExtInfo.getIdCard());// 身份证（）
            bizParamMap.put("sex", memberExtInfo.getSex()==1?2:1);// 性别
            bizParamMap.put("age", memberExtInfo.getAge());// 年龄
            bizParamMap.put("mobile", memberExtInfo.getMobile());// 	申请人手机号
            bizParamMap.put("order_sn", orderNo);// 	唯一订单号

            // 需要设置默认值
            bizParamMap.put("monthly_income_type", 1902);// 工资/收入发放方式
            bizParamMap.put("business_license", 1200);// 营业执照
            bizParamMap.put("career", 1100);// 职业
            bizParamMap.put("education_level", 1003);// 教育
            bizParamMap.put("wld", 700);// 微粒贷
            bizParamMap.put("credit_card_limit", 604);// 信用卡额度
            bizParamMap.put("demand_days", 12*30);// 贷款天数

            Long timestamp = System.currentTimeMillis();

            String sign = this.getSignResult(formInfo.getApiKey(), timestamp, formInfo.getApiSecret());
            String bizParam = this.getBizParamEncrypt(JSON.toJSONString(bizParamMap), formInfo.getApiSecret());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("channel", formInfo.getApiKey());
            paramMap.put("timestamp", timestamp);
            paramMap.put("sign", sign);
            paramMap.put("bizParam", bizParam);
            paramMap.putAll(bizParamMap);

            log.info("【快乐分期】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【快乐分期】导单结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);
            Integer status = resultObject.getInteger("status");
            String info = resultObject.getString("info");
            JSONObject data = resultObject.getJSONObject("data");

            pushResultDTO.setResult(result);
            pushResultDTO.setCode(String.valueOf(status));
            pushResultDTO.setMessage(info);
            pushResultDTO.setParamContent(JSON.toJSONString(bizParamMap));
            if (ObjectUtil.equal(status, Integer.valueOf(1))){
                String orderSn = data.getString("order_sn");
                pushResultDTO.setSuccess(true);
                pushResultDTO.setOutOrderNo(orderSn);
                pushResultDTO.setPushResult(PushResultEnum.SUCCESS.getType());
            }else{
                pushResultDTO.setPushResult(PushResultEnum.FAILED.getType());
                pushResultDTO.setSuccess(false);
            }
            return pushResultDTO;
    }

    /**
     * 获取签名数据
     * @param apiKey
     * @param timestamp
     * @param apiSecret
     * @return
     */
    private String getSignResult(String apiKey, Long timestamp, String apiSecret) {
        String signStr = StrUtil.format("{}&{}&{}", apiKey, timestamp, apiSecret);
        return SecureUtil.md5(signStr);
    }

    /**
     * 业务数据加密
     * @param content
     * @param key
     * @return
     */
    public String getBizParamEncrypt(String content, String key) throws Exception {
        byte[] originalContent = content.getBytes(StandardCharsets.UTF_8);
        byte[] encryptKey = key.getBytes();

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");;
        SecretKeySpec skeySpec = new SecretKeySpec(encryptKey, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(originalContent);
        return Base64.encodeBase64String(encrypted);

    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }

}
